<template>
  <div class="threat-container">
    <div class="header">
      <div class="title">
        <div class="title">
          <el-date-picker
            v-model.number="selectDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled-date="disabledDate"
            :default-value="defaultTime"
            value-format="YYYY-MM-DD"
            size="small"
          />
          <el-button type="primary" size="small" icon="Aim" @click="calc">计算威胁度</el-button>
        </div>
        <el-button type="primary" size="small" @click="saveConfig">保存</el-button>
      </div>
      <div class="config-item">
        <div class="config-item__title">综合权重配置</div>
        <div class="config-item__content">
          <div>
            <div class="item_title">
              <span>静态属性评估权重</span> <span>{{ config.weights.static }}%</span>
            </div>
            <el-slider v-model.number="config.weights.static" size="small" />
          </div>
          <div>
            <div class="item_title">
              <span>持续关系评估权重</span> <span>{{ config.weights.persistent }}%</span>
            </div>
            <el-slider v-model.number="config.weights.persistent" size="small" />
          </div>
          <div>
            <div class="item_title">
              <span>瞬时事件评估权重</span> <span>{{ config.weights.instant }}%</span>
            </div>
            <el-slider v-model.number="config.weights.instant" size="small" />
          </div>
        </div>
      </div>
      <div class="config-item">
        <div class="config-item__title">静态属性评估配置</div>
        <div class="config-item__content">
          <div>
            <div class="item_title">
              <span>国家权重</span> <span>{{ config.static_weights.country }}%</span>
            </div>
            <el-slider v-model.number="config.static_weights.country" size="small" />
          </div>
          <div>
            <div class="item_title">
              <span>轨道类型权重</span> <span>{{ config.static_weights.orbit_type }}%</span>
            </div>
            <el-slider v-model.number="config.static_weights.orbit_type" size="small" />
          </div>
          <div>
            <div class="item_title">
              <span>卫星类型权重</span> <span>{{ config.static_weights.sat_type }}%</span>
            </div>
            <el-slider v-model.number="config.static_weights.sat_type" size="small" />
          </div>
        </div>
      </div>
      <div class="config-item">
        <div class="config-item__title">持续关系评估配置</div>
        <div class="config-item__content">
          <div>
            <div class="item_title">
              <span>轨道相似权重</span> <span>{{ config.persistent_weights.orbit_similarity }}%</span>
            </div>
            <el-slider v-model.number="config.persistent_weights.orbit_similarity" size="small" />
          </div>
          <div>
            <div class="item_title">
              <span>轨道共面权重</span> <span>{{ config.persistent_weights.orbital_coplanarity }}%</span>
            </div>
            <el-slider v-model.number="config.persistent_weights.orbital_coplanarity" size="small" />
          </div>
          <div>
            <div class="item_title">
              <span>相位稳定权重</span> <span>{{ config.persistent_weights.phase_stability }}%</span>
            </div>
            <el-slider v-model.number="config.persistent_weights.phase_stability" size="small" />
          </div>
        </div>
      </div>
      <div class="config-item">
        <div class="config-item__title">国家威胁评分</div>
        <div class="config-item_score">
          <div>
            <span>美国</span>
            <el-input type="number" v-model.number="config.country_scores.美国" class="input-value"></el-input>
          </div>
          <div>
            <span>日本</span>
            <el-input type="number" v-model.number="config.country_scores.日本" class="input-value"></el-input>
          </div>
          <div>
            <span>俄罗斯</span>
            <el-input type="number" v-model.number="config.country_scores.俄罗斯" class="input-value"></el-input>
          </div>
          <div>
            <span>英国</span>
            <el-input type="number" v-model.number="config.country_scores.英国" class="input-value"></el-input>
          </div>
          <div>
            <span>法国</span>
            <el-input type="number" v-model.number="config.country_scores.法国" class="input-value"></el-input>
          </div>
          <div>
            <span>印度</span>
            <el-input type="number" v-model.number="config.country_scores.印度" class="input-value"></el-input>
          </div>
          <div>
            <span>其他</span>
            <el-input type="number" v-model.number="config.country_scores.其他" class="input-value"></el-input>
          </div>
        </div>
      </div>
      <div class="config-item">
        <div class="config-item__title">轨道类型评分</div>
        <div class="config-item_score">
          <div>
            <span>低轨</span>
            <el-input type="number" v-model.number="config.orbit_scores.低轨" class="input-value"></el-input>
          </div>
          <div>
            <span>中轨</span>
            <el-input type="number" v-model.number="config.orbit_scores.中轨" class="input-value"></el-input>
          </div>
          <div>
            <span>高轨</span>
            <el-input type="number" v-model.number="config.orbit_scores.高轨" class="input-value"></el-input>
          </div>
          <div>
            <span>大椭圆</span>
            <el-input type="number" v-model.number="config.orbit_scores.大椭圆" class="input-value"></el-input>
          </div>
          <div>
            <span>未知</span>
            <el-input type="number" v-model.number="config.orbit_scores.未知" class="input-value"></el-input>
          </div>
        </div>
      </div>
      <div class="config-item">
        <div class="config-item__title">卫星类型评分</div>
        <div class="config-item_score">
          <div>
            <span>实时侦察监视类</span>
            <el-input
              type="number"
              v-model.number="config.sat_type_scores.实时侦察监视类"
              class="input-value"
            ></el-input>
          </div>
          <div>
            <span>通信干扰类</span>
            <el-input type="number" v-model.number="config.sat_type_scores.通信干扰类" class="input-value"></el-input>
          </div>
          <div>
            <span>导航定位类</span>
            <el-input type="number" v-model.number="config.sat_type_scores.导航定位类" class="input-value"></el-input>
          </div>
          <div>
            <span>气象支持类</span>
            <el-input type="number" v-model.number="config.sat_type_scores.气象支持类" class="input-value"></el-input>
          </div>
          <div>
            <span>通用军事类</span>
            <el-input type="number" v-model.number="config.sat_type_scores.通用军事类" class="input-value"></el-input>
          </div>
          <div>
            <span>军民两用类</span>
            <el-input type="number" v-model.number="config.sat_type_scores.军民两用类" class="input-value"></el-input>
          </div>
          <div>
            <span>科研教育类</span>
            <el-input type="number" v-model.number="config.sat_type_scores.科研教育类" class="input-value"></el-input>
          </div>
        </div>
      </div>
      <div class="config-item">
        <div class="config-item__title">持续关系分段规则</div>
        <div class="config-item_gx">
          <div class="config-item_cx">
            <div class="title-gd">轨道相似</div>
            <div class="config-item__cx">
              <div>
                <span>半长轴差bins(km)</span>
                <el-input
                  v-model="config.persistent_scoring_rules.orbit_similarity.delta_sma_bins"
                  placeholder="请输入数字，多个用逗号分割"
                  class="input-value"
                ></el-input>
              </div>
              <div>
                <span>半长轴差分段得分</span>
                <el-input
                  v-model="config.persistent_scoring_rules.orbit_similarity.delta_sma_scores"
                  placeholder="请输入数字，多个用逗号分割"
                  class="input-value"
                ></el-input>
              </div>
              <div>
                <span>倾角差bins(rad)</span>
                <el-input
                  v-model="config.persistent_scoring_rules.orbit_similarity.delta_inc_bins"
                  placeholder="请输入数字，多个用逗号分割"
                  class="input-value"
                ></el-input>
              </div>
              <div>
                <span>倾角差分段得分</span>
                <el-input
                  placeholder="请输入数字，多个用逗号分割"
                  v-model="config.persistent_scoring_rules.orbit_similarity.delta_inc_scores"
                  class="input-value"
                ></el-input>
              </div>
              <div>
                <span>偏心率差 bins</span>
                <el-input
                  placeholder="请输入数字，多个用逗号分割"
                  v-model="config.persistent_scoring_rules.orbit_similarity.delta_ecc_bins"
                  class="input-value"
                ></el-input>
              </div>
              <div>
                <span>偏心率差分段得分 bins</span>
                <el-input
                  placeholder="请输入数字，多个用逗号分割"
                  v-model="config.persistent_scoring_rules.orbit_similarity.delta_ecc_scores"
                  class="input-value"
                ></el-input>
              </div>
            </div>
          </div>
          <div class="config-item_cx">
            <div class="title-gd">轨道共面性</div>
            <div class="config-item__cx">
              <div>
                <span>轨道面距bins(deg)</span>
                <el-input
                  placeholder="请输入数字，多个用逗号分割"
                  v-model="config.persistent_scoring_rules.orbital_coplanarity.plane_distance_bins"
                  class="input-value"
                ></el-input>
              </div>
              <div>
                <span>轨道面距分段得分</span>
                <el-input
                  placeholder="请输入数字，多个用逗号分割"
                  v-model="config.persistent_scoring_rules.orbital_coplanarity.plane_distance_scores"
                  class="input-value"
                ></el-input>
              </div>
            </div>
          </div>
          <div class="config-item_cx">
            <div class="title-gd">相位稳定</div>
            <div class="config-item__cx">
              <div>
                <span>Δu标准差bins</span>
                <el-input
                  placeholder="请输入数字，多个用逗号分割"
                  v-model="config.persistent_scoring_rules.phase_stability.delta_u_bins"
                  class="input-value"
                ></el-input>
              </div>
              <div>
                <span>Δu分段得分</span>
                <el-input
                  placeholder="请输入数字，多个用逗号分割"
                  v-model="config.persistent_scoring_rules.phase_stability.delta_u_scores"
                  class="input-value"
                ></el-input>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="config-item">
        <div class="config-item__title">抵近侦察分段规则</div>
        <div class="config-item_gx">
          <div class="config-item_cx">
            <div class="title-gd">抵近事件</div>
            <div class="config-item__cx">
              <div>
                <span>距离bins(km)</span>
                <el-input
                  placeholder="请输入数字，多个用逗号分割"
                  v-model="config.instant_scoring_rules.close_encounter.distance_bins_km"
                  class="input-value"
                ></el-input>
              </div>
              <div>
                <span>距离分段得分</span>
                <el-input
                  placeholder="请输入数字，多个用逗号分割"
                  v-model="config.instant_scoring_rules.close_encounter.distance_scores"
                  class="input-value"
                ></el-input>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="main">
      <div class="count">
        <div>
          <span>{{ statistics.days }}</span
          ><span>分析天数</span>
        </div>
        <div>
          <span>{{ statistics.unitCount }}</span
          ><span>分析单位数量</span>
        </div>
        <div>
          <span>{{ statistics.highThreatCount }}</span
          ><span>极高威胁目标</span>
        </div>
        <div>
          <span>{{ statistics.avgScore.toFixed(2) }}</span
          ><span>平均威胁分数</span>
        </div>
      </div>
      <div class="graph-container">
        <div class="graph-title">
          <el-icon><Search /></el-icon>威胁情况分析
        </div>
        <div class="search-bar">
          <el-input class="search-input" v-model="searchInput" placeholder="请输入卫星编号/国家名称" clearable />
          <el-button type="primary" icon="Aim" @click="handleSingleAnalysis">单星分析</el-button>
          <el-button type="primary" icon="PriceTag" @click="handleCountyAnalysis">关键词分析</el-button>
          <el-button type="primary" icon="Refresh" @click="handleReset">重置全部</el-button>
        </div>
        <div class="graph-desc">
          威胁分析的时间演变趋势。可以观察到威胁水平在分析期间保持相对稳定，但在特定时间段出现了显著的威胁集中现象，这与地缘政治事件和卫星的活动模式高度相关。
        </div>

        <div class="graph-grid">
          <div id="charts1" />
          <div id="charts2" v-if="notSingle" />
          <div id="charts3" />
          <div id="charts4" />
          <!-- <div id="charts7" /> -->
        </div>

        <div class="graph-title">
          <el-icon><List /></el-icon>卫星威胁度列表
        </div>
        <div class="graph-desc">
          <el-table style="width: 100%" :data="threatList">
            <el-table-column prop="satellite_id" label="卫星编号" />
            <el-table-column prop="name_en" label="卫星名称" />
            <el-table-column prop="country" label="国家" width="180" />
            <el-table-column prop="orbit_type" label="轨道类型" />
            <el-table-column prop="sat_type" label="卫星类型" />
            <el-table-column prop="threat_score" label="威胁度" sortable />
            <el-table-column prop="threat_level" label="威胁等级" />

            <el-table-column prop="preDate" label="预测日期" />
          </el-table>
          <div class="page">
            <el-pagination layout="prev, pager, next" :total="total" @current-change="handleCurrentPageChange">
            </el-pagination>
          </div>
        </div>
        <div class="graph-title">
          <el-icon><Comment /></el-icon>发现与建议措施
        </div>

        <div class="graph-desc">
          {{ suggestion }}
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { nextTick, onActivated, reactive, ref } from 'vue'
import * as echarts from 'echarts'
import {
  avgThreatAnalysis,
  calThreatAnalysis,
  getSatelliteThreatList,
  getSceneConfig,
  getSuggestionOfTask,
  highThreatAnalysis,
  saveSceneConfig,
  threatLevelAnalysis,
  threatStatisticsCount,
  variationThreatAnalysis,
} from '@/api/dashboard'
import { useLayoutStore } from '@/store/modules/layout'
import { ElMessage } from 'element-plus'
const selectDate = ref([])
const defaultTime = ref<[Date, Date]>([new Date(2025, 6, 3), new Date(2025, 6, 10)])
function disabledDate(time: Date) {
  const min = new Date('2025-07-03')
  const max = new Date('2025-09-29')
  if (time < min || time > max) return true
  return false
}

const calc = async () => {
  const res = await calThreatAnalysis(store.activedTaskId!, selectDate.value[0], selectDate.value[1])
  if (res.code === 200) {
    ElMessage.success('威胁度计算成功')
  } else {
    ElMessage.warning(res.msg)
  }
}

const store = useLayoutStore()
const searchInput = ref<string | number>(store.selectedSatellite?.norad ?? '')

let config = ref<SceneConfig>({
  taskId: store.activedTaskId!,
  weights: {
    static: 0,
    persistent: 0,
    instant: 0,
  },
  persistent_weights: {
    orbit_similarity: 0,
    orbital_coplanarity: 0,
    phase_stability: 0,
  },
  static_weights: {
    country: 0,
    orbit_type: 0,
    sat_type: 0,
  },
  country_scores: {
    美国: 0,
    日本: 0,
    英国: 0,
    法国: 0,
    印度: 0,
    俄罗斯: 0,
    其他: 0,
  },
  orbit_scores: {
    低轨: 0,
    大椭圆: 0,
    中轨: 0,
    高轨: 0,
    未知: 0,
  },
  sat_type_scores: {
    实时侦察监视类: 0,
    通信干扰类: 0,
    导航定位类: 0,
    气象支持类: 0,
    通用军事类: 0,
    军民两用类: 0,
    科研教育类: 0,
  },
  persistent_scoring_rules: {
    orbit_similarity: {
      delta_sma_bins: '',
      delta_sma_scores: '',
      delta_inc_bins: '',
      delta_inc_scores: '',
      delta_ecc_bins: '',
      delta_ecc_scores: '',
    },
    orbital_coplanarity: {
      plane_distance_bins: '',
      plane_distance_scores: '',
    },
    phase_stability: {
      delta_u_bins: '',
      delta_u_scores: '',
    },
  },
  instant_scoring_rules: {
    close_encounter: {
      distance_bins_km: '',
      distance_scores: '',
    },
  },
})

const saveConfig = async () => {
  config.value.weights.static = Math.round(config.value.weights.static * 100) / 10000
  config.value.weights.persistent = Math.round(config.value.weights.persistent * 100) / 10000
  config.value.weights.instant = Math.round(config.value.weights.instant * 100) / 10000
  config.value.persistent_weights.orbit_similarity =
    Math.round(config.value.persistent_weights.orbit_similarity * 100) / 10000
  config.value.persistent_weights.orbital_coplanarity =
    Math.round(config.value.persistent_weights.orbital_coplanarity * 100) / 10000
  config.value.persistent_weights.phase_stability =
    Math.round(config.value.persistent_weights.phase_stability * 100) / 10000
  config.value.static_weights.country = Math.round(config.value.static_weights.country * 100) / 10000
  config.value.static_weights.orbit_type = Math.round(config.value.static_weights.orbit_type * 100) / 10000
  config.value.static_weights.sat_type = Math.round(config.value.static_weights.sat_type * 100) / 10000

  config.value.persistent_scoring_rules.orbit_similarity.delta_sma_bins = String(
    config.value.persistent_scoring_rules.orbit_similarity.delta_sma_bins
  ).split(',') as unknown as number[]
  config.value.persistent_scoring_rules.orbit_similarity.delta_sma_scores = String(
    config.value.persistent_scoring_rules.orbit_similarity.delta_sma_scores
  ).split(',') as unknown as number[]
  config.value.persistent_scoring_rules.orbit_similarity.delta_inc_bins = String(
    config.value.persistent_scoring_rules.orbit_similarity.delta_inc_bins
  ).split(',') as unknown as number[]
  config.value.persistent_scoring_rules.orbit_similarity.delta_inc_scores = String(
    config.value.persistent_scoring_rules.orbit_similarity.delta_inc_scores
  ).split(',') as unknown as number[]
  config.value.persistent_scoring_rules.orbit_similarity.delta_ecc_bins = String(
    config.value.persistent_scoring_rules.orbit_similarity.delta_ecc_bins
  ).split(',') as unknown as number[]
  config.value.persistent_scoring_rules.orbit_similarity.delta_ecc_scores = String(
    config.value.persistent_scoring_rules.orbit_similarity.delta_ecc_scores
  ).split(',') as unknown as number[]
  config.value.persistent_scoring_rules.orbital_coplanarity.plane_distance_bins = String(
    config.value.persistent_scoring_rules.orbital_coplanarity.plane_distance_bins
  ).split(',') as unknown as number[]
  config.value.persistent_scoring_rules.orbital_coplanarity.plane_distance_scores = String(
    config.value.persistent_scoring_rules.orbital_coplanarity.plane_distance_scores
  ).split(',') as unknown as number[]
  config.value.persistent_scoring_rules.phase_stability.delta_u_bins = String(
    config.value.persistent_scoring_rules.phase_stability.delta_u_bins
  ).split(',') as unknown as number[]
  config.value.persistent_scoring_rules.phase_stability.delta_u_scores = String(
    config.value.persistent_scoring_rules.phase_stability.delta_u_scores
  ).split(',') as unknown as number[]
  config.value.instant_scoring_rules.close_encounter.distance_bins_km = String(
    config.value.instant_scoring_rules.close_encounter.distance_bins_km
  ).split(',') as unknown as number[]
  config.value.instant_scoring_rules.close_encounter.distance_scores = String(
    config.value.instant_scoring_rules.close_encounter.distance_scores
  ).split(',') as unknown as number[]
  config.value.taskId = store.activedTaskId!
  const res = await saveSceneConfig(config.value)
  if (res.code === 200) {
    getConfig()
    ElMessage.success('保存成功')
  }
}
function initGraph1(optData: { date: string; avgThreatScore: number }[]) {
  const chartDom = document.getElementById('charts1')
  const charts1 = echarts.init(chartDom)
  const option = {
    title: {
      text: '每日平均威胁分数趋势',
      textStyle: {
        color: '#eee',
        fontSize: 12,
      },
    },
    xAxis: {
      type: 'category',
      data: optData.map((s) => s.date),
      axisLine: {
        lineStyle: {
          color: '#eee', // X轴颜色
        },
      },
      axisTick: {
        lineStyle: {
          color: '#eee',
        },
      },
      axisLabel: {
        color: '#eee',
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#eee', // Y轴颜色
        },
      },
      axisTick: {
        lineStyle: {
          color: '#eee',
        },
      },
      axisLabel: {
        color: '#eee',
      },
    },
    series: [
      {
        data: optData.map((s) => s.avgThreatScore),
        type: 'line',
        lineStyle: {
          color: '#bd2424', // 折线颜色
          width: 2,
        },
        symbol: 'none', // ← 去掉拐点
      },
    ],
  }
  option && charts1.setOption(option)
}
function initGraph2(optData: { date: string; variation: number }[]) {
  const chartDom = document.getElementById('charts2')
  const charts2 = echarts.init(chartDom)
  const option = {
    title: {
      text: '威胁分数波动性分析',
      textStyle: {
        color: '#eee',
        fontSize: 12,
      },
    },
    xAxis: {
      type: 'category',
      data: optData.map((s) => s.date),
      axisLine: {
        lineStyle: {
          color: '#eee', // X轴颜色
        },
      },
      axisTick: {
        lineStyle: {
          color: '#eee',
        },
      },
      axisLabel: {
        color: '#eee',
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#eee', // Y轴颜色
        },
      },
      axisTick: {
        lineStyle: {
          color: '#eee',
        },
      },
      axisLabel: {
        color: '#eee',
      },
    },
    series: [
      {
        data: optData.map((s) => s.variation),
        type: 'line',
        lineStyle: {
          color: '#1e90ff', // 折线颜色
          width: 2,
        },
        symbol: 'none', // ← 去掉拐点
      },
    ],
  }
  option && charts2.setOption(option)
}
function initGraph3(optData: { date: string; count: number }[]) {
  const chartDom = document.getElementById('charts3')
  const charts3 = echarts.init(chartDom)
  const option = {
    title: {
      text: '高威胁卫星数量变化',
      textStyle: {
        color: '#eee',
        fontSize: 12,
      },
    },
    xAxis: {
      type: 'category',
      data: optData.map((s) => s.date),
      axisLine: {
        lineStyle: {
          color: '#eee', // X轴颜色
        },
      },
      axisTick: {
        lineStyle: {
          color: '#eee',
        },
      },
      axisLabel: {
        color: '#eee',
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#eee', // Y轴颜色
        },
      },
      axisTick: {
        lineStyle: {
          color: '#eee',
        },
      },
      axisLabel: {
        color: '#eee',
      },
    },
    series: [
      {
        data: optData.map((s) => s.count),
        type: 'line',
        lineStyle: {
          color: '#67C23A', // 折线颜色
          width: 2,
        },
        symbol: 'none', // ← 去掉拐点
      },
    ],
  }
  option && charts3.setOption(option)
}
function initGraph4(optData: Record<string, number>) {
  const chartDom = document.getElementById('charts4')
  const charts4 = echarts.init(chartDom)
  const option = {
    title: {
      text: '威胁等级分布演变',
      textStyle: {
        color: '#eee',
        fontSize: 12,
      },
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      bottom: 15,
      textStyle: {
        color: '#eee',
      },
    },
    series: [
      {
        name: '威胁等级',
        type: 'pie',
        radius: '50%',
        data: Object.entries(optData).map(([key, value]) => ({ value, name: key })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }
  option && charts4.setOption(option)
}
// function initGraph7() {
//   const chartDom = document.getElementById('charts7')
//   const charts7 = echarts.init(chartDom)
//   const option = {
//     title: {
//       text: '威胁目标热力图',
//       textStyle: {
//         color: '#eee',
//         fontSize: 12,
//       },
//     },
//     xAxis: {
//       type: 'category',
//       data: ['10', '11', '12', '13', '14', '15', '16'],
//       axisLine: {
//         lineStyle: {
//           color: '#eee', // X轴颜色
//         },
//       },
//       axisTick: {
//         lineStyle: {
//           color: '#eee',
//         },
//       },
//       axisLabel: {
//         color: '#eee',
//       },
//     },
//     yAxis: {
//       type: 'value',
//       axisLine: {
//         lineStyle: {
//           color: '#eee', // Y轴颜色
//         },
//       },
//       axisTick: {
//         lineStyle: {
//           color: '#eee',
//         },
//       },
//       axisLabel: {
//         color: '#eee',
//       },
//     },
//     // 2. 颜色标尺：y 越大越深
//     visualMap: {
//       type: 'continuous', // 连续型
//       dimension: 1, // 1 表示用数据的第 2 维（y 值）
//       orient: 'vertical',
//       right: 10,
//       top: 'center',
//       min: 0, // 可改为你数据的真实最小 y
//       max: 10, // 可改为你数据的真实最大 y
//       inRange: {
//         color: ['#e0f3ff', '#4575b4', '#d73027'], // 浅 → 深
//       },
//     },
//     series: [
//       {
//         symbolSize: 20,
//         data: [
//           [10.0, 8.04],
//           [8.07, 6.95],
//           [13.0, 7.58],
//           [9.05, 8.81],
//           [11.0, 8.33],
//           [14.0, 7.66],
//           [13.4, 6.81],
//           [10.0, 6.33],
//           [14.0, 8.96],
//           [12.5, 6.82],
//           [9.15, 7.2],
//           [11.5, 7.2],
//           [3.03, 4.23],
//           [12.2, 7.83],
//           [2.02, 4.47],
//           [1.05, 3.33],
//           [4.05, 4.96],
//           [6.03, 7.24],
//           [12.0, 6.26],
//           [12.0, 8.84],
//           [7.08, 5.82],
//           [5.02, 5.68],
//         ],
//         type: 'scatter',
//       },
//     ],
//   }
//   option && charts7.setOption(option)
// }
function handleSingleAnalysis() {
  if (searchInput.value.toString().trim() === '') {
    ElMessage.warning('请输入卫星编号')
    return
  }
  if (isNaN(Number(searchInput.value))) {
    ElMessage.warning('请输入正确的卫星编号')
    return
  }
  notSingle.value = false
  initGraphs('1')
  getThreatList(1, Number(searchInput.value))
}
function handleCountyAnalysis() {
  if (searchInput.value.toString().trim() === '') {
    ElMessage.warning('请输入国家名称')
    return
  }
  notSingle.value = true
  initGraphs('2')
  getThreatList(1, undefined, String(searchInput.value))
}
function handleReset() {
  notSingle.value = true
  loadDataAll()
  getThreatList()
}
function initGraphs(searchType: string) {
  if (searchType && searchType === '1') {
    loadDataBySatelliteId()
  } else if (searchType && searchType === '2') {
    loadDataBySateCountry()
  } else {
    loadDataAll()
  }
}

async function loadDataAll() {
  searchInput.value = ''
  store.setSelectedSatellite(null)
  const avg = await avgThreatAnalysis(store.activedTaskId!)
  if (avg.code === 200) {
    initGraph1(avg.data)
  }
  const variation = await variationThreatAnalysis(store.activedTaskId!)
  if (variation.code === 200) {
    initGraph2(variation.data)
  }
  const high = await highThreatAnalysis(store.activedTaskId!)
  if (high.code === 200) {
    initGraph3(high.data)
  }
  const imp = await threatLevelAnalysis(store.activedTaskId!)
  if (imp.code === 200) {
    initGraph4(imp.data)
  }
}

async function loadDataBySatelliteId() {
  const avg = await avgThreatAnalysis(store.activedTaskId!, Number(searchInput.value))
  if (avg.code === 200) {
    initGraph1(avg.data)
  }

  const high = await highThreatAnalysis(store.activedTaskId!, Number(searchInput.value))
  if (high.code === 200) {
    initGraph3(high.data)
  }
  const imp = await threatLevelAnalysis(store.activedTaskId!, Number(searchInput.value))
  if (imp.code === 200) {
    initGraph4(imp.data)
  }
}
async function loadDataBySateCountry() {
  const avg = await avgThreatAnalysis(store.activedTaskId!, undefined, String(searchInput.value))
  if (avg.code === 200) {
    initGraph1(avg.data)
  }
  const variation = await variationThreatAnalysis(store.activedTaskId!, String(searchInput.value))
  if (variation.code === 200) {
    initGraph2(variation.data)
  }
  const high = await highThreatAnalysis(store.activedTaskId!, undefined, String(searchInput.value))
  if (high.code === 200) {
    initGraph3(high.data)
  }
  const imp = await threatLevelAnalysis(store.activedTaskId!, undefined, String(searchInput.value))
  if (imp.code === 200) {
    initGraph4(imp.data)
  }
}
const statistics = reactive({
  days: 0,
  unitCount: 0,
  highThreatCount: 0,
  avgScore: 0,
})
const suggestion = ref('')
async function getSuggestion() {
  if (store.activedTaskId) {
    const res = await getSuggestionOfTask(store.activedTaskId)
    if (res.code === 200) suggestion.value = res.data
  }
}
const getConfig = async () => {
  const r = await getSceneConfig(store.activedTaskId!)
  if (r.code === 200) {
    if (r.data.user_overrides) {
      r.data.user_overrides.weights.static = Math.round(r.data.user_overrides.weights.static * 100)
      r.data.user_overrides.weights.persistent = Math.round(r.data.user_overrides.weights.persistent * 100)
      r.data.user_overrides.weights.instant = Math.round(r.data.user_overrides.weights.instant * 100)
      r.data.user_overrides.persistent_weights.orbit_similarity = Math.round(
        r.data.user_overrides.persistent_weights.orbit_similarity * 100
      )
      r.data.user_overrides.persistent_weights.orbital_coplanarity = Math.round(
        r.data.user_overrides.persistent_weights.orbital_coplanarity * 100
      )
      r.data.user_overrides.persistent_weights.phase_stability = Math.round(
        r.data.user_overrides.persistent_weights.phase_stability * 100
      )
      r.data.user_overrides.static_weights.country = Math.round(r.data.user_overrides.static_weights.country * 100)
      r.data.user_overrides.static_weights.orbit_type = Math.round(
        r.data.user_overrides.static_weights.orbit_type * 100
      )
      r.data.user_overrides.static_weights.sat_type = Math.round(r.data.user_overrides.static_weights.sat_type * 100)
      config.value = r.data.user_overrides
    }
  }
}
const threatList = ref<SatelliteThreat[]>([])
const getThreatList = async (page: number = 1, satelliteId?: number, country?: string) => {
  if (store.activedTaskId) {
    let res
    if (satelliteId) {
      res = await getSatelliteThreatList(store.activedTaskId, page, 10, satelliteId)
    } else if (country) {
      res = await getSatelliteThreatList(store.activedTaskId, page, 10, undefined, country)
    } else {
      res = await getSatelliteThreatList(store.activedTaskId, page, 10)
    }

    if (res.code === 200) {
      threatList.value = res.data.content
      total.value = res.data.totalElements
    }
  }
}
const total = ref(0)
const handleCurrentPageChange = (page: number) => {
  getThreatList(page)
}
const notSingle = ref(true)
onActivated(() => {
  nextTick(async () => {
    const resC = await threatStatisticsCount(store.activedTaskId!)
    if (resC.code === 200) {
      const { avgScore, days, highThreatCount, unitCount } = resC.data
      statistics.avgScore = avgScore
      statistics.days = days
      statistics.highThreatCount = highThreatCount
      statistics.unitCount = unitCount
    }
    if (store.selectedSatellite) {
      searchInput.value = store.selectedSatellite.norad
      notSingle.value = false
      initGraphs('1')
    } else {
      notSingle.value = true
      initGraphs('')
    }

    // initGraph7()
    // 建议
    getSuggestion()
    // 参数
    getConfig()
    // 威胁度
    getThreatList(1, store.selectedSatellite?.norad)
  })
})
</script>
<style lang="scss" scoped>
.threat-container {
  .header {
    padding: 10px;
    .title {
      display: flex;
      gap: 10px;
      justify-content: flex-end;
    }
    .config-item {
      .input-value {
        width: 220px;
      }
      padding-top: 20px;
      display: grid;
      grid-template-columns: 200px 1fr;
      font-size: 14px;
      gap: 20px;
      padding: 5px 0;
      .config-item__title {
        text-align: right;
        font-weight: bold;
        color: #4277ac;
        font-size: 16px;
      }
      .config-item_gx {
        display: flex;
        flex-direction: column;

        .config-item_cx {
          display: flex;
          flex-direction: column;
          .title-gd {
            padding-bottom: 10px;
            font-weight: bold;
            color: #408340;
          }
          & > div {
            display: flex;
          }
          .config-item__cx {
            display: flex;
            gap: 10px;
            div {
              display: flex;
              flex-direction: column;
              span {
                text-align: left;
              }
            }
          }
        }
      }

      .config-item_score {
        display: flex;
        gap: 10px;
        & > div {
          display: flex;
          flex-direction: column;
          span {
            text-align: left;
          }
        }
      }
      .config-item__content {
        width: 30%;
        display: flex;
        align-items: center;
        justify-content: start;
        gap: 30px;
        div {
          width: 300px;
        }
        .item_title {
          display: flex;
          justify-content: space-between;
        }
        :deep(.atlas-app-slider) {
          padding: 0 10px;
        }
      }
    }
  }
  .main {
    padding: 10px;
    .count {
      display: flex;
      gap: 10px;
      justify-content: space-between;
      & > div {
        background: #1f4a76;
        display: flex;
        flex: 1;
        flex-direction: column;
        align-items: center;
        padding: 5px;
        & > span:first-child {
          font-size: 18px;
          font-weight: bold;
        }
      }
    }
    .graph-container {
      .graph-title {
        display: flex;
        align-items: center;
        gap: 2px;
        padding: 10px 0;
        color: #b3b3b3;
        font-weight: bold;
      }
      .search-bar {
        display: flex;
        gap: 10px;
        padding: 30px 20%;
        justify-content: center;
        .search-input {
          padding-right: 10px;
          width: 200px;
        }
      }
      .graph-desc {
        padding: 5px;
        background: #1f4a76;
        text-align: left;
        margin-bottom: 5px;
      }
      .graph-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        grid-auto-rows: minmax(220px, auto);
        gap: 5px;
        & > div {
          background: #1f4a76;
        }
      }
    }
  }
}
</style>
